import whisper
import opencc
import time

from moviepy.editor import VideoFileClip

import os

from socketio import Client

from cpu_api import GetExtract

import threading

import spacy
import json
from collections import Counter
import jieba.analyse

# 加载spaCy中文模型
nlp = spacy.load("D:\AtomGit\model\spacy\zh_core_web_sm\zh_core_web_sm-3.7.0")


sio = Client()
    
socket_flag = 0  # socketio连接标识
    
model = whisper.load_model("base")
print("----------- whisper 加载成功 -----------")

def analyze_text(text, top_k_keywords=10, top_k_frequent=10):
    # 使用jieba提取关键词
    keywords = jieba.analyse.extract_tags(text, topK=top_k_keywords)

    # 使用spaCy处理文本，计算高频词
    doc = nlp(text)
    word_freq = Counter([token.text for token in doc if not token.is_punct])
    frequent_words = [word for word, freq in word_freq.most_common(top_k_frequent)]

    # 构建节点
    data_nodes = [{"group": "Event", "id": 1, "label": "关键词"},
                  {"group": "Event", "id": 2, "label": "高频词"}]
    node_id = 3  # 从3开始分配ID
    node_map = {"关键词": 1, "高频词": 2}
    for word in set(keywords + frequent_words):
        data_nodes.append({"group": "Event", "id": node_id, "label": word})
        node_map[word] = node_id
        node_id += 1

    # 构建边，连接关键词和高频词
    data_edges = []
    for keyword in keywords:
        data_edges.append({"from": node_map[keyword], "label": "", "to": 1})  # 连接到“关键词”
    for frequent_word in frequent_words:
        data_edges.append({"from": node_map[frequent_word], "label": "", "to": 2})  # 连接到“高频词”

    return data_nodes, data_edges

def graph_generate(file_path):
    # 测试文本

    test_text = 0
    # 打开文件并读取内容
    with open(file_path, 'r', encoding='utf-8') as file:
        test_text = file.read()

        data_nodes, data_edges = analyze_text(test_text)

        nodes_json = json.dumps(data_nodes, ensure_ascii=False)
        edges_json = json.dumps(data_edges, ensure_ascii=False)
   
        sio.emit('transformer_graph', {'nodes_json':nodes_json, 'edges_json':edges_json}, namespace='/transformer_')

def send_message_to_server1(message):
    sio.emit('transformer_message', {'message': message}, namespace='/transformer_')
    
def send_textpath(message):
    sio.emit('transformer_textpath', {'message': message}, namespace='/transformer_')

def execute_threads(text_path, time_path, extract_path, json_path, video_name):
    # 定义两个线程，分别执行 text_get 和 GetExtract 函数
    
    context_path = "contexts/" + video_name
    thread1 = threading.Thread(target=send_textpath, args=("contexts",))
    thread2 = threading.Thread(target=GetExtract, args=(text_path, time_path, extract_path, json_path, video_name))
    thread3 = threading.Thread(target=graph_generate, args=(text_path,))

    # 启动线程
    thread1.start()
    thread2.start()
    thread3.start()

    # 等待线程执行完毕
    thread1.join()
    thread2.join()
    thread3.join()

def delete_files_in_folder(folder_path):
    # 遍历文件夹中的所有文件
    for file_name in os.listdir(folder_path):
        # 构建文件的绝对路径
        file_path = os.path.join(folder_path, file_name)
        try:
            # 删除文件
            if os.path.isfile(file_path):
                os.remove(file_path)
            # 如果是文件夹，则递归删除文件夹中的文件
            elif os.path.isdir(file_path):
                delete_files_in_folder(file_path)
        except Exception as e:
            print("",end='')

def transformerVideoToAudio(video_path,
                            audio_path,
                            video_name,
                            video_tag):
    
    global socket_flag
    if (socket_flag == 0):
        sio.connect('http://127.0.0.1:8090', namespaces=['/transformer_'])
        
    socket_flag = 1
    
    try:
        video = VideoFileClip(video_path)
        audio = video.audio
        audio.write_audiofile(audio_path)
        print("----------- 音频提取完成！-----------")
    except Exception as e:
        print("提取音频时出错：", e)
    # 创建 Socket.IO 客户端
    time_1=time.time()
    
    
    print("----------- 音频转录中... -----------")
    send_message_to_server1(10)
        
    text_path = "text/" + video_name + ".txt"
    time_path = "text/" + video_name + "_time.txt"
    json_path = "data/" + video_name + ".json"
    
    # 使用 os.makedirs() 创建文件夹，如果文件夹已存在则不会报错
    
    
    context_dir_path = "contexts/" + video_name
    
    # os.makedirs(context_dir_path, exist_ok=True)
    
    # context_path = "contexts/" + video_name + "/" + video_name + ".txt"
    
    context_path = "contexts/" + video_name + ".txt"

    converter=opencc.OpenCC("t2s.json") 
    # 转录音频
    
    send_message_to_server1(30)
    result = model.transcribe(audio_path, word_timestamps=True, language="Chinese")
    
    send_message_to_server1(50)
    
    # 获取"segments"键对应的值
    with open (text_path,"w",encoding="utf-8") as f:
        result_text=result['text']
        result_text=converter.convert(result_text)
        f.write(result_text)
        print("----------- 音频转录完成! -----------")
    with open (context_path,"w",encoding="utf-8") as f:
        result_text=result['text']
        result_text=converter.convert(result_text)
        f.write(result_text)
    time_2=time.time()
    print(f"----------- 音频转录总耗时：{time_2-time_1}秒 -----------")

    #打开一个.txt文件以写入"segments"的内容
    segments = result.get("segments")

    if segments is not None:
        with open(time_path, "w", encoding="utf-8") as txt_file:
            for segment in segments:
                start_time = segment.get("start")
                end_time = segment.get("end")
                text = segment.get("text")
                text=converter.convert(text)
                txt_file.write(f"start:{start_time} --> end:{end_time} {text}\n")
    else:
        print("segments键不存在于result字典中。")
        
    extract_path = "text/" + video_name + "_extract.txt"
    
    execute_threads(text_path, time_path, extract_path, json_path, video_name)
    
    # text_get(text_path)
    
    # GetExtract(text_path, time_path, extract_path, json_path, video_name)
    
    
    # 调用函数删除指定文件夹下的全部文件
    folder_path = r'temp'
    delete_files_in_folder(folder_path)
    print("----------- 处理完成！-----------")
   

    
# if __name__=="__main__":
    
#     # 创建并启动新进程
#     sio.connect('http://127.0.0.1:8090', namespaces=['/transformer_'])

#     client_process = multiprocessing.Process(target=run_client)
#     client_process.start()
#     # 解析参数
#     params = {}
#     for i in range(1, len(sys.argv), 2):
#         params[sys.argv[i]] = sys.argv[i+1]
        
#     print(params['--param1'])
#     print(params['--param2'])
#     print(params['--param3'])
#     print(params['--param4'])
  
#     transformerVideoToAudio(params['--param1'], params['--param2'], params['--param3'], params['--param4'])

